<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="MySQL事务的4种隔离级别1 简介事务的4种隔离级别分别是读未提交（Read Uncommitted）、读已提交（Read Committed）、 可重复读（Repeatable Read）和串行化（Serializable）。 首先，在了解这4种隔离级别前就必须先要了解其前提，也就是事务，本文简单介绍一下关于事务。 之后，我们也要理解这4种隔离级别产生的原因和场景展现以及4种隔离级别是如何解决">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL事务的4种隔离级别">
<meta property="og:url" content="http://littlefxc.github.io/2022/04/15/docs/MySQL/MySQL%E4%BA%8B%E5%8A%A1%E7%9A%844%E7%A7%8D%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="MySQL事务的4种隔离级别1 简介事务的4种隔离级别分别是读未提交（Read Uncommitted）、读已提交（Read Committed）、 可重复读（Repeatable Read）和串行化（Serializable）。 首先，在了解这4种隔离级别前就必须先要了解其前提，也就是事务，本文简单介绍一下关于事务。 之后，我们也要理解这4种隔离级别产生的原因和场景展现以及4种隔离级别是如何解决">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_0.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_1.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_2.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_3.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_4-20220415155652729.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_5.png">
<meta property="article:published_time" content="2022-04-14T23:47:13.000Z">
<meta property="article:modified_time" content="2022-05-10T01:23:06.652Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="mysql">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_0.png">


<link rel="canonical" href="http://littlefxc.github.io/2022/04/15/docs/MySQL/MySQL%E4%BA%8B%E5%8A%A1%E7%9A%844%E7%A7%8D%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>MySQL事务的4种隔离级别 | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#MySQL%E4%BA%8B%E5%8A%A1%E7%9A%844%E7%A7%8D%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB"><span class="nav-text">MySQL事务的4种隔离级别</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#1-%E7%AE%80%E4%BB%8B"><span class="nav-text">1 简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-%E4%BB%80%E4%B9%88%E6%98%AF%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BA%8B%E5%8A%A1%EF%BC%9F"><span class="nav-text">2 什么是数据库事务？</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-%E4%BA%8B%E5%8A%A1%E7%9A%84%E5%9B%9B%E5%A4%A7%E7%89%B9%E6%80%A7%EF%BC%88ACID%EF%BC%89"><span class="nav-text">2.1 事务的四大特性（ACID）</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-%E5%B9%B6%E5%8F%91%E4%BA%8B%E5%8A%A1%E4%BC%9A%E5%AF%BC%E8%87%B4%E7%9A%84%E9%97%AE%E9%A2%98"><span class="nav-text">3 并发事务会导致的问题</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-%E6%9C%AC%E6%96%87%E4%BC%9A%E4%BD%BF%E7%94%A8%E5%88%B0%E7%9A%84-SQL-%E8%AF%AD%E5%8F%A5%EF%BC%9A"><span class="nav-text">3.1 本文会使用到的 SQL 语句：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-1-%E7%A4%BA%E4%BE%8B%E8%A1%A8%E7%BB%93%E6%9E%84"><span class="nav-text">3.1.1 示例表结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-2-%E6%9F%A5%E8%AF%A2%E4%BA%8B%E5%8A%A1%E7%9A%84%E9%BB%98%E8%AE%A4%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB"><span class="nav-text">3.1.2 查询事务的默认隔离级别</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-3-%E8%AE%BE%E7%BD%AE%E5%BD%93%E5%89%8D%E4%BC%9A%E8%AF%9D%E7%9A%84%E4%BA%8B%E5%8A%A1%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB"><span class="nav-text">3.1.3 设置当前会话的事务隔离级别</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-%E4%BA%8B%E5%8A%A1%E7%9A%844%E7%A7%8D%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB%E5%92%8C%E7%A4%BA%E4%BE%8B%E6%BC%94%E7%A4%BA"><span class="nav-text">4 事务的4种隔离级别和示例演示</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-%E8%AF%BB%E6%9C%AA%E6%8F%90%E4%BA%A4"><span class="nav-text">4.1 读未提交</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-%E8%AF%BB%E5%B7%B2%E6%8F%90%E4%BA%A4"><span class="nav-text">4.2 读已提交</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8F%90%E4%BA%A4%E8%AF%BB%E7%9A%84%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB%E4%BC%9A%E6%9C%89%E4%BB%80%E4%B9%88%E9%97%AE%E9%A2%98%E5%91%A2%EF%BC%9F"><span class="nav-text">提交读的隔离级别会有什么问题呢？</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-3-%E5%8F%AF%E9%87%8D%E5%A4%8D%E8%AF%BB"><span class="nav-text">4.3 可重复读</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%82%A3%E4%B9%88%E5%8F%AF%E9%87%8D%E5%A4%8D%E8%AF%BB%E7%9C%9F%E7%9A%84%E6%98%AF%E5%90%A6%E5%B7%B2%E7%BB%8F%E8%A7%A3%E5%86%B3%E4%BA%86%E5%B9%BB%E8%AF%BB%E9%97%AE%E9%A2%98%E5%91%A2%EF%BC%9F%E6%AF%95%E7%AB%9F%E8%BF%98%E5%89%A9%E4%B8%AA%E4%BA%8B%E5%8A%A1%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB%E5%91%A2%E3%80%82"><span class="nav-text">那么可重复读真的是否已经解决了幻读问题呢？毕竟还剩个事务隔离级别呢。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B0%8F%E7%BB%93"><span class="nav-text">小结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-4-%E4%B8%B2%E8%A1%8C%E5%8C%96"><span class="nav-text">4.4 串行化</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%9B%B8%E5%85%B3%E6%80%A7"><span class="nav-text">相关性</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%96%87%E7%8C%AE%E5%BC%95%E7%94%A8"><span class="nav-text">文献引用</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2022/04/15/docs/MySQL/MySQL%E4%BA%8B%E5%8A%A1%E7%9A%844%E7%A7%8D%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          MySQL事务的4种隔离级别
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-04-15 07:47:13" itemprop="dateCreated datePublished" datetime="2022-04-15T07:47:13+08:00">2022-04-15</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2022-05-10 09:23:06" itemprop="dateModified" datetime="2022-05-10T09:23:06+08:00">2022-05-10</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" itemprop="url" rel="index"><span itemprop="name">数据库</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="MySQL事务的4种隔离级别"><a href="#MySQL事务的4种隔离级别" class="headerlink" title="MySQL事务的4种隔离级别"></a>MySQL事务的4种隔离级别</h1><h1 id="1-简介"><a href="#1-简介" class="headerlink" title="1 简介"></a>1 简介</h1><p>事务的4种隔离级别分别是读未提交（Read Uncommitted）、读已提交（Read Committed）、 可重复读（Repeatable Read）和串行化（Serializable）。</p>
<p>首先，在了解这4种隔离级别前就必须先要了解其前提，也就是事务，本文简单介绍一下关于事务。</p>
<p>之后，我们也要理解这4种隔离级别产生的原因和场景展现以及4种隔离级别是如何解决问题的。</p>
<h1 id="2-什么是数据库事务？"><a href="#2-什么是数据库事务？" class="headerlink" title="2 什么是数据库事务？"></a>2 什么是数据库事务？</h1><p>事务由一个有限的数据库操作序列组成，这些操作要么全部执行，要么全部不执行，是一个不可分割的工作单位。</p>
<p>例如一个银行转账场景：</p>
<p>A转账B 100元，A的账号扣除100元，B的账号加上100块。假如中间出现任何异常，例如，在A的账号扣100元时，银行瘫痪，B的账号余额没有发生变化。这时候就需要事务来保证将A的钱还回去。</p>
<h2 id="2-1-事务的四大特性（ACID）"><a href="#2-1-事务的四大特性（ACID）" class="headerlink" title="2.1 事务的四大特性（ACID）"></a>2.1 事务的四大特性（ACID）</h2><ul>
<li>原子性：事务作为一个整体被执行，包含在其中的对数据库的操作要么全部都执行，要么都不执行。</li>
<li>一致性：指在事务开始之前和事务结束以后，数据不会被破坏，假如A账户给B账户转10块钱，不管成功与否，A和B的总金额是不变的。</li>
<li>隔离性：多个事务并发访问时，事务之间是相互隔离的，一个事务不应该被其他事务干扰，多个并发事务之间要相互隔离。</li>
<li>持久性：表示事务完成提交后，该事务对数据库所作的操作更改，将持久地保存在数据库之中。</li>
</ul>
<h1 id="3-并发事务会导致的问题"><a href="#3-并发事务会导致的问题" class="headerlink" title="3 并发事务会导致的问题"></a>3 并发事务会导致的问题</h1><ul>
<li>脏读：事务 A 读取了事务 B 更新的数据，然后 B 进行回滚操作，那么A读取的数据就是脏数据</li>
<li>不可重复读：事务A多次读取同一数据，事务B在事务A多次读取的过程中，对数据做了更新并提交，导致事务A多次夺取同一数据时，结果不一致。</li>
<li>幻读：系统管理员A将数据库中所有学生的成绩从具体分数改为ABCDE等级，但是系统管理员B就在这个时候插入了一条具体分数的记录，当系统管理员A改结束后发现还有一条记录没有改过来，就好像发生了幻觉一样，这就叫幻读。</li>
</ul>
<blockquote>
<p>💡 不可重复读的和幻读很容易混淆，不可重复读侧重于修改，幻读侧重于新增或删除。解决不可重复读的问题只需锁住满足条件的行，解决幻读需要锁表。</p>
</blockquote>
<h2 id="3-1-本文会使用到的-SQL-语句："><a href="#3-1-本文会使用到的-SQL-语句：" class="headerlink" title="3.1 本文会使用到的 SQL 语句："></a>3.1 本文会使用到的 SQL 语句：</h2><h3 id="3-1-1-示例表结构"><a href="#3-1-1-示例表结构" class="headerlink" title="3.1.1 示例表结构"></a>3.1.1 示例表结构</h3><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> `account` (</span><br><span class="line">  `id` <span class="type">int</span>(<span class="number">11</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">  `name` <span class="type">varchar</span>(<span class="number">255</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">  `balance` <span class="type">int</span>(<span class="number">11</span>) <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">  <span class="keyword">PRIMARY</span> KEY (`id`),</span><br><span class="line">  <span class="keyword">UNIQUE</span> KEY `un_name_idx` (`name`) <span class="keyword">USING</span> BTREE</span><br><span class="line">) ENGINE<span class="operator">=</span>InnoDB <span class="keyword">DEFAULT</span> CHARSET<span class="operator">=</span>utf8;</span><br></pre></td></tr></table></figure>

<h3 id="3-1-2-查询事务的默认隔离级别"><a href="#3-1-2-查询事务的默认隔离级别" class="headerlink" title="3.1.2 查询事务的默认隔离级别"></a>3.1.2 查询事务的默认隔离级别</h3><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> @<span class="variable">@transaction</span>_isolation;</span><br><span class="line"><span class="operator">+</span><span class="comment">-------------------------+</span></span><br><span class="line"><span class="operator">|</span> @<span class="variable">@transaction</span>_isolation <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">-------------------------+</span></span><br><span class="line"><span class="operator">|</span> REPEATABLE<span class="operator">-</span>READ         <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">-------------------------+</span></span><br><span class="line"><span class="number">1</span> <span class="type">row</span> <span class="keyword">in</span> <span class="keyword">set</span> (<span class="number">0.01</span> sec)</span><br></pre></td></tr></table></figure>

<h3 id="3-1-3-设置当前会话的事务隔离级别"><a href="#3-1-3-设置当前会话的事务隔离级别" class="headerlink" title="3.1.3 设置当前会话的事务隔离级别"></a>3.1.3 设置当前会话的事务隔离级别</h3><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">set</span> session transaction isolation level read uncommitted;</span><br><span class="line">Query OK, <span class="number">0</span> <span class="keyword">rows</span> affected (<span class="number">0.00</span> sec)</span><br></pre></td></tr></table></figure>

<h1 id="4-事务的4种隔离级别和示例演示"><a href="#4-事务的4种隔离级别和示例演示" class="headerlink" title="4 事务的4种隔离级别和示例演示"></a>4 事务的4种隔离级别和示例演示</h1><table>
<thead>
<tr>
<th>事务隔离级别</th>
<th>脏读</th>
<th>不可重复读</th>
<th>幻读</th>
</tr>
</thead>
<tbody><tr>
<td>读未提交（read-uncommitted）</td>
<td>是</td>
<td>是</td>
<td>是</td>
</tr>
<tr>
<td>不可重复读（read-committed）又叫读已提交</td>
<td>否</td>
<td>是</td>
<td>是</td>
</tr>
<tr>
<td>可重复读（repeatable-read）</td>
<td>否</td>
<td>否</td>
<td>是</td>
</tr>
<tr>
<td>串行化（serializable）</td>
<td>否</td>
<td>否</td>
<td>否</td>
</tr>
</tbody></table>
<h2 id="4-1-读未提交"><a href="#4-1-读未提交" class="headerlink" title="4.1 读未提交"></a>4.1 读未提交</h2><p>事务A：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_0.png" alt="Untitled"></p>
<p>事务B：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_1.png" alt="Untitled"></p>
<blockquote>
<p>💡 读未提交是隔离级别最低的，会造成脏读。</p>
</blockquote>
<h2 id="4-2-读已提交"><a href="#4-2-读已提交" class="headerlink" title="4.2 读已提交"></a>4.2 读已提交</h2><p>为了避免脏读，数据库有了比<strong>读未提交</strong>更高的隔离级别，即<strong>读已提交</strong>。</p>
<p>对于提交：当前事务只能读取其它事务已提交的数据，未提交事务的数据读取不到。</p>
<p>事务A：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_2.png" alt="Untitled"></p>
<p>事务B：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_3.png" alt="Untitled"></p>
<p>由此可以得出结论，隔离级别设置为<strong>已提交读（READ COMMITTED）</strong><br> 时，已经不会出现脏读问题了，当前事务只能读取到其他事务提交的数据。但是，站在事务A的角度想想，存在其他问题吗？</p>
<h3 id="提交读的隔离级别会有什么问题呢？"><a href="#提交读的隔离级别会有什么问题呢？" class="headerlink" title="提交读的隔离级别会有什么问题呢？"></a><strong>提交读的隔离级别会有什么问题呢？</strong></h3><p>在同一个事务A里，相同的查询sql，读取同一条记录（id=1），读到的结果是不一样的，即<strong>不可重复读</strong>。所以，隔离级别设置为<code>read committed</code>的时候，还会存在<strong>不可重复读</strong>的并发问题。</p>
<h2 id="4-3-可重复读"><a href="#4-3-可重复读" class="headerlink" title="4.3 可重复读"></a>4.3 可重复读</h2><p>为了避免<strong>不可重复读</strong>的并发问题，我们将隔离级别设置为<strong>可重复读（REPEATABLEE READ）</strong>，重复一下之前的操作。</p>
<p>事务A：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_4-20220415155652729.png" alt="Untitled"></p>
<p>事务B：</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_5.png" alt="Untitled"></p>
<p><a target="_blank" rel="noopener" href="https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_5.png">https://gitee.com/littlefxc/oss/raw/master/images/mysql_transaction_5.png</a></p>
<p>到了这一步，可以发现事务隔离级别设置为可重复读，可以解决幻读问题。</p>
<h3 id="那么可重复读真的是否已经解决了幻读问题呢？毕竟还剩个事务隔离级别呢。"><a href="#那么可重复读真的是否已经解决了幻读问题呢？毕竟还剩个事务隔离级别呢。" class="headerlink" title="那么可重复读真的是否已经解决了幻读问题呢？毕竟还剩个事务隔离级别呢。"></a>那么<strong>可重复读</strong>真的是否已经解决了幻读问题呢？毕竟还剩个事务隔离级别呢。</h3><p>RR隔离级别下，手动启动一个事务，进行select操作，他会生成一个快照，可以理解为将当前数据库的数据复制一份，在当前事务中，之后不管进行多少次select查询，都是在模板中去取数据，所以不管数据库中是否对数据进行了改变，都不会影响当前事务数据的读取，从而避免了幻读。<strong>这种普通的 select 操作，称为快照读</strong>。</p>
<p>但是如果在当前事务中使用了下图语句进行<strong>当前读</strong>:</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> account <span class="keyword">for</span> update;</span><br></pre></td></tr></table></figure>

<p><code>for update</code>是进行<strong>当前读</strong>的操作，他会重新从数据库去加载当前的最新的数据，每执行一次加载一次，如果在此时，另外一个事务为数据库添加了一个事务，再进行查询，会发现查询的数据与之前相比多了或者少了，这也就是幻读现象。</p>
<p>如果你阅读到这里，去实操一下，会发现和我说的不一样，有一种上当的感觉。</p>
<p>其实不是的，这是因为上述都是在标准的可重复读下的情况，在innodb存储引擎中对可重复读进行了改造，为当前读加上了 <code>Next-key Lock</code>,也就是间隙锁和行锁的统称，<strong>行锁防止了别的事务修改或者删除，间隙锁防止了别的事务新增</strong>。也就是在进行上面的<code>for update</code>事务中，其他的事务不能对数据进行增删操作，执行会报错或者长时间处于等待状态。</p>
<blockquote>
<p>💡 注意：如果A事务如果进行了快照读，然后通过B事务对数据就行增删，然后紧接着A事务进行当前读操作，两次读取数据不一致，不能算作幻读，因为幻读定义是同一个select语句，快照读和当前读的查询语句是不一样的.</p>
</blockquote>
<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><ol>
<li><strong>数据库的并发问题有：脏读、不可重复读和幻读；</strong></li>
<li><strong>事务隔离级别依次为：读未提交、读已提交、可重复读和串行化；</strong></li>
<li><strong>在标准的RR下并没有彻底解决幻读，但是在Mysql的innodb引擎中彻底解决了；</strong></li>
<li><strong>innodb通过</strong> Next-Key lock<strong>解决的幻读问题，其实也就是阻塞串行化了；</strong></li>
<li><strong>不能把快照读和当前读在一个事务中进行比较是否出现幻读，两者不是同一个select，不满足幻读的官方定义。</strong></li>
</ol>
<h2 id="4-4-串行化"><a href="#4-4-串行化" class="headerlink" title="4.4 串行化"></a>4.4 串行化</h2><p>略，这部分我懒得放图了，因为结果和上面没啥差别。</p>
<h1 id="相关性"><a href="#相关性" class="headerlink" title="相关性"></a>相关性</h1><hr>
<h1 id="文献引用"><a href="#文献引用" class="headerlink" title="文献引用"></a>文献引用</h1><hr>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/jay-huaxiao/p/12639435.html">一文彻底读懂MySQL事务的四大隔离级别 - Jay_huaxiao - 博客园</a></p>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/yaochunhui/p/14177906.html">MySQL的四种事务隔离级别</a></p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_45225798/article/details/119978841">关于数据库隔离级别为RR(可重复读)下是否解决幻读问题_眉梢i的博客-CSDN博客_rr解决幻读</a></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/mysql/" rel="tag"># mysql</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/04/07/docs/%E5%BE%AE%E6%9C%8D%E5%8A%A1/RocketMQ%E4%BA%8B%E5%8A%A1%E6%B6%88%E6%81%AF%E7%A4%BA%E4%BE%8B/" rel="prev" title="RocketMQ事务消息示例">
                  <i class="fa fa-chevron-left"></i> RocketMQ事务消息示例
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/04/20/docs/%E5%BE%AE%E6%9C%8D%E5%8A%A1/Gateway/" rel="next" title="Gateway">
                  Gateway <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
